/**
 * @filename:ContractServiceImpl 2021-11-09 01:40:35
 * @project com/lwl/blue  V1.0
 * Copyright(c) 2018 <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a> Co. Ltd.
 * All right reserved.
 */
package com.lwl.blue.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lwl.blue.commont.base.BizException;
import com.lwl.blue.commont.base.ErrorCode;
import com.lwl.blue.commont.base.JsonResult;
import com.lwl.blue.commont.base.PageParam;
import com.lwl.blue.commont.enums.ExcelTemplateEnum;
import com.lwl.blue.commont.utils.DateUtils;
import com.lwl.blue.commont.utils.EasyExcelUtils;
import com.lwl.blue.commont.utils.ExcelTemplateUtil;
import com.lwl.blue.dao.ContractDao;
import com.lwl.blue.entity.Contract;
import com.lwl.blue.entity.ContractDetail;
import com.lwl.blue.entity.Customer;
import com.lwl.blue.excel.contract.CreateSupplierContractDetailExport;
import com.lwl.blue.excel.contract.CreateSupplierContractExport;
import com.lwl.blue.service.ContractDetailService;
import com.lwl.blue.service.ContractService;
import com.lwl.blue.service.CustomerService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.MathContext;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>自定义serviceImpl写在这里</p>
 *
 * <p>说明： 合同表服务实现层</P>
 *
 * @version: V1.0
 * @author: <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a>
 */
@Service
public class ContractServiceImpl extends ServiceImpl<ContractDao, Contract> implements ContractService {
    @Resource
    private ContractDao contractDao;
    @Resource
    private ContractDetailService contractDetailService;
    @Resource
    private CustomerService customerService;

    @Override
    public JsonResult<Page<Contract>> pages(PageParam<Contract> pageParam) {
        Page<Contract> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
        return new JsonResult<Page<Contract>>().success(contractDao.pages(page, pageParam.getParam()));
    }

    @Override
    public void createCustomerContract(HttpServletResponse response, Integer id) {
        Contract contract = contractDao.selectById(id);
        List<ContractDetail> list = contractDetailService.list(new QueryWrapper<ContractDetail>()
                .lambda()
                .eq(ContractDetail::getContractId, id)
                .eq(ContractDetail::getIsDelete, 0));
//        EasyExcelUtils.exportTemplate(response,"客人合同",ExcelTemplateUtil.getExcelTemplatePath(ExcelTemplateEnum.CONTRACT_CUSTOMER),);
    }

    @Override
    public void createSupplierContract(HttpServletResponse response, Integer contractId, Integer supplierId) {
        Contract contract = contractDao.selectById(contractId);
        CreateSupplierContractExport createSupplierContractExport = new CreateSupplierContractExport();
        List<ContractDetail> detailList = contractDetailService.list(new QueryWrapper<ContractDetail>()
                .lambda()
                .eq(ContractDetail::getContractId, contractId)
                .eq(ContractDetail::getSupplierId, supplierId)
                .eq(ContractDetail::getIsDelete, 0));
        if(detailList.isEmpty()){
            throw new BizException(ErrorCode.CONTRACT_DETAIL_NOT_EXIST_ERROR.getCode(),ErrorCode.CONTRACT_DETAIL_NOT_EXIST_ERROR.getMsg());
        }
        BeanUtils.copyProperties(contract, createSupplierContractExport);
        Customer customer = customerService.getById(contract.getCustomerId());
        createSupplierContractExport.setCustomerName(customer.getCustomerName());
        List<CreateSupplierContractDetailExport> list = new ArrayList<>();
        BigDecimal sumInnerBoxNumber = BigDecimal.ZERO;
        BigDecimal sumBoxNumber = BigDecimal.ZERO;
        BigDecimal sumTotalPrice = BigDecimal.ZERO;
        for (ContractDetail d : detailList) {
            CreateSupplierContractDetailExport c = new CreateSupplierContractDetailExport();
            BeanUtils.copyProperties(d, c);
            c.setPhoto(EasyExcelUtils.getURL(d.getPhoto()));
            c.setDeliveryDate(DateUtils.formatLocalDate(LocalDate.now(), "yyyy-MM-dd"));
            c.setTotalPrice(c.getInnerBoxNumber().multiply(c.getSupplierPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
            list.add(c);
            sumInnerBoxNumber = sumInnerBoxNumber.add(c.getInnerBoxNumber());
            sumBoxNumber = sumBoxNumber.add(c.getBoxNumber());
            sumTotalPrice = sumTotalPrice.add(c.getTotalPrice());
        }
        createSupplierContractExport.setSumInnerBoxNumber(sumInnerBoxNumber);
        createSupplierContractExport.setSumBoxNumber(sumBoxNumber);
        createSupplierContractExport.setSumTotalPrice(sumTotalPrice);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String templateFileName = ExcelTemplateUtil.getExcelTemplatePath(ExcelTemplateEnum.CONTRACT_SUPPLIER);
        try {
            String rFileName = URLEncoder.encode("工厂合同", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + rFileName + ".xlsx");
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(templateFileName).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            // 如果有多个list 模板上必须有{前缀.} 这里的前缀就是 data1，然后多个list必须用 FillWrapper包裹
            excelWriter.fill(new FillWrapper("list", list), fillConfig, writeSheet);
            excelWriter.fill(createSupplierContractExport, writeSheet);
            // 别忘记关闭流
            excelWriter.finish();
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new BizException(ErrorCode.SYS_EXCEPTION.getCode(),ErrorCode.SYS_EXCEPTION.getMsg());

        }

    }


}